import React, {Component} from 'react';
import './todoList.css'

class TodoList extends Component {
    constructor(props) {
        super(props);
        this.state = {  
            list: []
        };
    }
    addData=()=>{
        // console.log(this.refs.title.value);
        if(!this.refs.title.value){return}
        var tempList = this.state.list;
        tempList.unshift(this.refs.title.value);  // 返回值是一个索引值
        this.refs.title.value = ''; // 让input的值变为空
        this.setState({
            list: tempList
        })
    }
    removeData=(key)=>{
        // console.log(key);
        var tempList = this.state.list;
        tempList.splice(key, 1);
        this.setState({
            list: tempList
        })
    }
    inputKeyUp=(e)=>{
        if(e.keyCode === 13){
            this.addData();
        }
    }
    render() {
        return (
            <div>
                <h2>React Todolist 案例演示</h2>
                <input ref="title" onKeyUp={this.inputKeyUp}/><button onClick={this.addData}>增加+</button>
                <br/>
                <ul className="list">
                    {
                        this.state.list.map((value, key)=>{
                            return(
                                <li key={key}>{value}----<button onClick={this.removeData.bind(this,key)}>删除-</button></li>
                            )
                        })
                    }
                </ul>
            </div>
        );
    }
}

export default TodoList;